import Utf8 from "crypto-js/enc-utf8";
import CryptoAes from "crypto-js/aes";
import FormatHex from "crypto-js/format-hex";
import Base64Url from "crypto-js/enc-base64url";
import Hex from "crypto-js/enc-hex";

const key = "com.ftefscrm.ui";
const hexKey = Utf8.parse(key).toString(Hex);

export function AsciiCode(str) {
  const hexArr = Utf8.parse(str).toString(Hex).split("");
  // 针对hex和hexkey进行异或运算
  const xorStr = hexArr.map((m, i) => {
    const hexKeyItem = hexKey[i % hexKey.length];
    const hexKeyItemNum = parseInt(hexKeyItem, 16);
    const hexItemNum = parseInt(m, 16);
    const xorNum = hexItemNum ^ hexKeyItemNum;
    return xorNum.toString(16);
  }).join("");
  // 把或位运算后的结果转换回 Crypto-js 的 WordArray
  return Base64Url.stringify(Hex.parse(xorStr));
}
export function DeAsciiCode(str) {
  const hexArr = Base64Url.parse(str).toString(Hex).split("");
  // 针对hex和hexkey进行异或运算
  const xorStr = hexArr.map((m, i) => {
    const hexKeyItem = hexKey[i % hexKey.length];
    const hexKeyItemNum = parseInt(hexKeyItem, 16);
    const hexItemNum = parseInt(m, 16);
    const xorNum = hexItemNum ^ hexKeyItemNum;
    return xorNum.toString(16);
  }).join("");
  // 把或位运算后的结果转换回 原始的值
  return Hex.parse(xorStr).toString(Utf8);
}
//! aes 每次加密结果都是不一样的
export function AesEncrypt(str: string) {
  return CryptoAes.encrypt(str, key).toString(FormatHex);
}
export function AesDecrypt(str: string) {
  return CryptoAes.decrypt(FormatHex.parse(str), key).toString(Utf8);
}
